package com.lanou.liuqixin.datebasedemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanou.liuqixin.datebasedemo.R;

import java.util.List;

import db.CarEntity;

/**
 * Created by dllo on 17/4/25.
 */

public class ListViewAdapter extends BaseAdapter {
    private List<CarEntity> mCarEntities;
    private Context mContext;
    private ListViewHolder mListViewHolder;

    public ListViewAdapter(List<CarEntity> carEntities, Context context) {
        mCarEntities = carEntities;
        mContext = context;

    }

    @Override
    public int getCount() {
        return mCarEntities.size();
    }

    @Override
    public Object getItem(int position) {
        return mCarEntities.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mCarEntities.get(position).get_id();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        mListViewHolder = new ListViewHolder();
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_listview, parent, false);
            mListViewHolder.itemTv = (TextView) convertView.findViewById(R.id.item_lv);
            mListViewHolder.delIv = (ImageView) convertView.findViewById(R.id.item_iv);
            convertView.setTag(mListViewHolder);
        } else {

            mListViewHolder = (ListViewHolder) convertView.getTag();
        }
        CarEntity carEntity = mCarEntities.get(position);
        mListViewHolder.itemTv.setText(carEntity.getName());

        mListViewHolder.delIv.setTag(carEntity);

        mListViewHolder.delIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnDelClickListener != null) {
                    CarEntity car = (CarEntity) v.getTag();
                    mOnDelClickListener.onDelClick(car);
                    mCarEntities.remove(position);
                    notifyDataSetChanged();

                }
            }
        });
        return convertView;
    }

    private OnDelClickListener mOnDelClickListener;

    public interface OnDelClickListener {
        void onDelClick(CarEntity car);
    }

    public void setOnDelClickListener(OnDelClickListener onDelClickListener) {
        mOnDelClickListener = onDelClickListener;
    }

    class ListViewHolder {
        TextView itemTv;
        ImageView delIv;
    }


}
